//
//  AppController.m
//  Friday
//
//  Created by josy on 12/13/09.
//  Copyright 2009 Apple. All rights reserved.
//

#import "AppController.h"
#import "MyGrowlDelegate.h"
#import "RadarOperation.h"
#import <Growl/GrowlApplicationBridge.h>
#import "MyRequest.h"
#import "JSON.h"
#import <Carbon/Carbon.h>

OSStatus myHotKeyHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData);

@implementation AppController

OSStatus myHotKeyHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData) {
	AppController* ctrl = ( AppController*) userData;
	
	EventHotKeyID hkCom;
	GetEventParameter(anEvent,kEventParamDirectObject,typeEventHotKeyID,NULL, sizeof(hkCom),NULL,&hkCom);
	int l = hkCom.id;
	
	//NSLog(@"Selectde Key is is %d" , l);
	
	[ctrl showActionForKey:l];
	return noErr;
}

-(void)showActionForKey:(int)asyncValueOfKey  {
	NSString* key = [NSString stringWithFormat:@"KEY_%d", asyncValueOfKey];
	currentRequest = (MyRequest*) [requestTemplates valueForKey:key];
	
	// Bring the app to front
	[win setLevel: NSFloatingWindowLevel];
	[[NSApplication sharedApplication] activateIgnoringOtherApps: YES];
	[win makeKeyAndOrderFront:nil];
	[win makeFirstResponder:sub ];
	[win setTitle:[currentRequest getMyWinTitle]];
	[sub setStringValue:[[currentRequest getTaskParams] valueForKey:@"subject" ]];
	[bdy setStringValue:[[currentRequest getTaskParams] valueForKey:@"body" ]];
}

-(IBAction)hideLogWindow:(id)sender {
	[logWin orderOut:win ];	
	
	[GrowlApplicationBridge notifyWithTitle:@"Closing Log Window" description:@"You can open this window by using CMD-L when app is active" 
						   notificationName:@"FridayNotfn" iconData:nil priority:0 isSticky:NO clickContext:@"rdar://problem/7247549"];
}

-(IBAction)showLogWindow:(id)sender {
	[logWin orderFront:win ];	
}

- (void)dealloc {
	[parser release];
	[growlDelegate release];
	[requestTemplates release];
	[inputTemplates release];
	[asyncKeyList release];
	[currentRequest release];
	[queue release];
	[super dealloc];
}

-(void)awakeFromNib {
	[win center];
	//[logWin center];
	[logWin makeKeyAndOrderFront:win];
	[self showLog:@"Loading Keymap.........."];
	[self loadAsyncKeys];
	[self showLog:@"Loading User Files ..........."];
	[self loadRequestData];
	[self showLog:@"Registering Global Keys ..........."];
	[self regGlobalKeys];
	[self showLog:@"Lauch Completed"];
	parser = [[SBJSON alloc] init];
	growlDelegate = [[MyGrowlDelegate alloc] init];
	queue = [[NSOperationQueue alloc] init];
	
	[GrowlApplicationBridge setGrowlDelegate:growlDelegate];
}

-(void)regGlobalKeys {
    EventTypeSpec eventType;
	eventType.eventClass=kEventClassKeyboard;
    eventType.eventKind=kEventHotKeyPressed;
	
	InstallApplicationEventHandler(&myHotKeyHandler,1,&eventType,self,NULL);
	
	EventHotKeyRef myHotKeyRef;
	
	for(NSString* key in [requestTemplates allKeys]) {
		MyRequest* req = (MyRequest*) [requestTemplates valueForKey:key];
		
		int kAsync = [req getAsyncKey];
		
		// This registers the hotkey
		EventHotKeyID myHotKeyIDx;
		myHotKeyIDx.signature= 99887700 + kAsync; // Unique 4 byte sequence
		myHotKeyIDx.id=kAsync; 
		RegisterEventHotKey(kAsync, cmdKey+optionKey+controlKey, myHotKeyIDx, GetApplicationEventTarget(), 0, &myHotKeyRef);
		
		//NSLog(@"Registered Key (%d) CMD-OPTION-CTRL-%@ for Action [%@]" , kAsync, [req getKCode], [req getMyWinTitle]);
		[self showLog:[NSString  stringWithFormat:@"Registered Key (%d) CMD-OPTION-CTRL-%@ for Action [%@]" , kAsync, [req getKCode], [req getMyWinTitle]]];
	}	
}

-(void)	showLog:(NSString*) line {
	//NSLog(line);
	[logTf setStringValue:[[logTf stringValue] stringByAppendingString:[NSString stringWithFormat:@"%@\n",line]]];
}

-(void)loadAsyncKeys {
	NSString* ff = [NSString stringWithFormat:@"%@/Contents/Resources/asyncKeys.plist", [[NSBundle mainBundle] bundlePath]];
	asyncKeyList = [[NSDictionary alloc] initWithContentsOfFile:ff];
}

-(void)loadRequestData {
	inputTemplates = [[NSMutableDictionary alloc] init];
	requestTemplates = [[NSMutableDictionary alloc] init];
	NSString *bundleRoot = [NSString stringWithFormat:@"%@/../data/", [[NSBundle mainBundle] bundlePath]];
	[self showLog:[NSString stringWithFormat:@"Root directory or files %@", bundleRoot]];
	
	//NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
	NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];
	for(NSString* fname in dirContents) {
		if([fname hasSuffix:@".plist"]) {
			@try {
				NSString* kCode = [[fname substringToIndex:1] lowercaseString];
				int aKey = [[asyncKeyList valueForKey:kCode] intValue];
				
				[self showLog:[NSString  stringWithFormat:@"LoadingFile %@", fname]];
				[self showLog:[NSString  stringWithFormat:@"Got async Key for %@ as %d", kCode, aKey]];
				
				NSString* key = [NSString stringWithFormat:@"KEY_%d", aKey];
				
				NSString* ff = [NSString stringWithFormat:@"%@%@",bundleRoot, fname];
				NSDictionary* dictionary2 = [[NSDictionary alloc] initWithContentsOfFile:ff];
				
				MyRequest* req = [[MyRequest alloc] init];
				[req setAsyncKey:aKey];
				[req setKCode:kCode];
				[req setMyWinTitle:[dictionary2 valueForKey:@"windowTitle"]];
				[req setTaskParams:[dictionary2 valueForKey:@"body"]];
				
				[requestTemplates setValue:req forKey:key];
			}
			@catch (NSException * e) {
				NSLog([e name]);
			}
		}
		if([fname hasSuffix:@".tmpl"]) {
			@try {
				NSString* templateName = [[fname componentsSeparatedByString:@"."] objectAtIndex:0];
				NSString* ff = [NSString stringWithFormat:@"%@%@",bundleRoot, fname];
				NSString *fileString = [NSString stringWithContentsOfFile:ff];
				
				[inputTemplates setValue:fileString forKey:templateName];
			}
			@catch (NSException * e) {
				NSLog([e name]);
			}	
		}
	}
}

-(IBAction)sendRequestToServer:(id)sender {
	//NSLog(@"OBUtton clicked");
	
	// currentRequest contains all details of the task o be excuted. 
	if(!currentRequest) {
		return;	
	}
	
	NSDictionary* taskParamsBodyHash = [currentRequest getTaskParams];
	NSString* subject = [sub stringValue];
	NSString* mybody = [bdy stringValue];
	//NSLog(@"Looking for key %@", [taskParamsBodyHash valueForKeyPath:@"inputTemplate"]);
	NSString* inputTemplate = [inputTemplates valueForKey:[taskParamsBodyHash valueForKeyPath:@"inputTemplate"]];
	
	RadarOperation* ro = [[RadarOperation alloc] initWithSubject:subject andBody:mybody andParams:taskParamsBodyHash andTemplate:inputTemplate];
	[queue addOperation: ro];
	//NSLog(@"
	
	[win orderOut:nil];
}

/*
-(void)sendMsg:(MyRequest*) myrequest;
{	
	
	@try {
		//NSString *post = [NSString stringWithFormat:@"%@", [bodyText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
		//NSString *post =  [NSString stringWithFormat:@"HAHAHAHAH is %@", [[NSDate alloc] init]]; 
		NSString* post = [parser stringWithObject:[myrequest getBody]];
		NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
		
		NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
		
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
		NSURL *url = [NSURL URLWithString:[myrequest getServer]];
		[request setURL:url];
		[request setHTTPMethod:@"POST"];
		[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
		[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
		[request setHTTPBody:postData];
		
		NSHTTPURLResponse *response;
		NSError *error;
		// We should probably be parsing the data returned by this call, for now just check the error.
		[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
		
		if (error != nil) {
			@throw [NSException exceptionWithName:[error description] reason:@"You are not on Apple network?" userInfo:nil];
		}
		
		if ([response statusCode] != 200) {
			@throw [NSException exceptionWithName:[NSString stringWithFormat:@"Server rejected your request (%d)", [response statusCode]] reason:@"Are you a valid user?" userInfo:nil];
		}
	}
	@catch (NSException* e) {
		NSRunCriticalAlertPanel([e name], [e reason], @"OK", nil, nil);
	}
}
 */

@end